/**
 * 个股排行榜数据钩子
 */

import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse, StockRankingResponse, RankingType, MarketType } from '@shared/types/market';
import { getRefreshInterval } from '@shared/utils/marketStatus';

const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

interface UseStockRankingOptions {
  type: RankingType;
  market?: MarketType;
  limit?: number;
  excludeST?: boolean;
}

/**
 * 获取个股排行榜数据
 */
export function useStockRanking({
  type,
  market = 'all',
  limit = 10,
  excludeST = true,
}: UseStockRankingOptions) {
  const refreshInterval = getRefreshInterval();
  
  return useQuery({
    queryKey: ['stockRanking', type, market, limit, excludeST],
    queryFn: async () => {
      const params = new URLSearchParams({
        type,
        market,
        limit: limit.toString(),
        exclude_st: excludeST.toString(),
      });

      const response = await get<ApiResponse<StockRankingResponse>>(
        `${API_BASE}/api/v1/market/ranking?${params.toString()}`
      );
      return response.data;
    },
    refetchInterval: refreshInterval, // 动态刷新间隔
    // 休市时增加 staleTime，避免频繁重新请求
    staleTime: refreshInterval === 0 ? 300000 : 15000, // 休市时5分钟，交易时15秒
    gcTime: 300000, // 缓存5分钟
    refetchOnWindowFocus: false,
    // 休市时禁用所有自动刷新
    refetchOnMount: refreshInterval > 0,
    refetchOnReconnect: refreshInterval > 0,
  });
}

